import React from 'react';
import { RangePickerCom } from './DatePickerCom.js';
import { Form, Button, Input, Radio, Row, Col, Space } from 'antd';
import './App.less';
const validator = [
  {
    validator: async (_, models) => {
      if (!models || models.length < 1) {
        return Promise.reject(new Error('至少配置一项'));
      }
    },
  },
];

const SelfRegistration = (props: any) => {
  const { index, deleteProcess, name } = props;
  const form = Form.useFormInstance();
  const parents = Form.useWatch('parents');
  const linkTypesItem = parents?.[name]?.linkTypes[index] ?? {};

  const getFormName = (field) => {
    return ['parents', name, 'linkTypes', index, field];
  };
  const setTimes = (startTime, endTime) => {
    form.setFieldValue(getFormName('startTime'), startTime);
    form.setFieldValue(getFormName('endTime'), endTime);
  };
  return (
    <div className="dot">
      <Row className="fx xj mb32">
        <Col span={22} className="fs16 b">
          环节{index + 1}（个体考评）
        </Col>
        <Col>
          {' '}
          <Button
            type="default"
            className="mt-10"
            onClick={() => {
              deleteProcess(index);
            }}
          >
            删除
          </Button>
        </Col>
      </Row>
      <Form.Item
        label="流环节名称："
        name={[index, 'name']}
        rules={[{ required: true, message: '请填写环节名称' }]}
      >
        <Input placeholder="配置当前教师考评环节的名称，如：教师自评，环节名称将显示在教师端" />
      </Form.Item>
      <Form.Item
        label="个体考评方式："
        name={[index, 'linkType']}
        rules={[{ required: true, message: '请选择考评方式!' }]}
      >
        <Radio.Group className="w ">
          <Radio value={0}>自评</Radio>
          <Radio value={1}>他评</Radio>
        </Radio.Group>
      </Form.Item>
      {linkTypesItem.linkType === 0 ? (
        <div>
          <Form.Item
            label="自评环节设置"
            name={[index, 'selfEvaluateType']}
            rules={[{ required: true, message: '请设置自评环节!' }]}
          >
            <Radio.Group className="w ">
              <Radio value={0}>
                <p>
                  仅自评结果
                  <span className="g9 fs12">
                    （仅自评结果，无需填写其他信息）
                  </span>
                </p>
              </Radio>
              <Radio value={1}>
                <p>
                  自评结果与自我评价相结合
                  <span className="g9 fs12">
                    （提交自评结果后，再填写自我评价，方便其他教师进行他评）
                  </span>
                </p>
              </Radio>
            </Radio.Group>
            {/* <RangePicker showTime className="w" /> */}
          </Form.Item>
          <Form.Item
            extra="注：在自评时间段内提交自评结果及自我评价信息；"
            label="自评时间设置"
            name={[index, 'dates']}
            rules={[{ required: true, message: '请选择时间!' }]}
          >
            <RangePickerCom
              showTime
              formatType="dateTimeMinute"
              // key={parents?.[name]?.link?.startTime}
              defaultValue={
                linkTypesItem?.startTime
                  ? [linkTypesItem?.startTime, linkTypesItem?.endTime]
                  : null
              }
              setValue={setTimes}
            />
            {/* <RangePicker showTime className="w" /> */}
          </Form.Item>
        </div>
      ) : (
        <>
          <Form.Item
            extra="注：在他评时间段内提交自评结果及自我评价信息"
            label="他评时间设置"
            name={[index, 'dates']}
            rules={[{ required: true, message: '请选择他评时间!' }]}
          >
            <RangePickerCom
              showTime
              formatType="dateTimeMinute"
              // key={parents?.[name]?.link?.startTime}
              defaultValue={
                linkTypesItem?.startTime
                  ? [linkTypesItem?.startTime, linkTypesItem?.endTime]
                  : null
              }
              setValue={setTimes}
            />
            {/* <RangePicker showTime className="w" /> */}
          </Form.Item>
        </>
      )}
      <Form.Item name={[index, 'startTime']} hidden></Form.Item>
      <Form.Item name={[index, 'endTime']} hidden></Form.Item>
    </div>
  );
};
const App = () => {
  const [form] = Form.useForm();
  const onFinish = (values) => {
    console.log('values: ', values);
  };
  const onFinishFailed = (error) => {
    console.log('values:errorFields ', error);
    let error_div = document.querySelectorAll('.ant-form-item-has-error');
    if (error_div.length) {
      error_div[0]?.scrollIntoView({
        block: 'center',
        behavior: 'smooth',
      });
    }
  };
  return (
    <section>
      <div>展示信息</div>
      <Form
        form={form}
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
        labelCol={{
          flex: '200px',
        }}
      >
        <Form.List name="parents" rules={validator}>
          {(fields, { add, remove }, { errors }) => (
            <>
              {fields.map(({ key, name, ...restField }) => (
                <section className="common-container mt24" key={name}>
                  <div style={{ textAlign: 'right' }}>
                    <Button
                      className="mb24"
                      type="primary"
                      onClick={() => remove(name)}
                    >
                      删除该考评分组下考评环节
                    </Button>
                  </div>

                  <Form.List name={[name, 'linkTypes']} rules={validator}>
                    {(
                      modelsList,
                      { add: addtest, remove: removetest },
                      { errors }
                    ) => (
                      <div>
                        <Form.Item
                          // name={[name, "teachers"]}
                          className="mt10"
                          label="添加考评分组："
                          required
                        >
                          <div className="mb40">
                            <div className="bgt r6px p24">
                              <Button
                                type="primary"
                                onClick={() => addtest({ type: 0 })}
                              >
                                添加该环节
                              </Button>
                            </div>
                          </div>
                        </Form.Item>
                        <div className=" ">
                          {modelsList.map((testItem) => {
                            return (
                              <div
                                className="process-list"
                                // key={`${name}-${testItem.name}`}
                              >
                                <SelfRegistration
                                  index={testItem.name}
                                  name={name}
                                  deleteProcess={removetest}
                                />
                              </div>
                            );
                          })}
                        </div>
                        <Form.Item className="m0" labelCol={{ flex: '128px' }}>
                          <Form.ErrorList errors={errors} />
                        </Form.Item>
                      </div>
                    )}
                  </Form.List>
                </section>
              ))}
              <Form.Item className="tc mt20 mb0">
                <Button
                  className=" bcf w c1 fs16"
                  style={{ height: 70, borderRadius: 12, width: '100%' }}
                  onClick={() => add()}
                  shape="default"
                  type="dashed"
                >
                  <i className="icon-icon_add_1 mr5" /> 添加新的考评分组
                </Button>
              </Form.Item>
              <Form.ErrorList className="mt20 c1 error" errors={errors} />
            </>
          )}
        </Form.List>
        <Button type="primary" htmlType="submit">
          保存
        </Button>
      </Form>
    </section>
  );
};

export default App;
